package com.easyfun.healthmagicbox.comm;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.easyfun.healthmagicbox.alarmclock.AlarmReceiver;
import com.easyfun.healthmagicbox.alarmclock.AlarmRepeatCalculater;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.json.AlarmClockListJsonWrapper;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.AlarmClock;
import com.easyfun.healthmagicbox.sync.CommCallback;
import com.easyfun.healthmagicbox.util.HealthDateUtil;
import com.easyfun.healthmagicbox.util.PersonProfileCache;
import com.j256.ormlite.dao.Dao;

public class AlarmClockDownloadTask extends BaseCommTask implements
		DatabaseAccess {

	private static final String TAG = AlarmClockDownloadTask.class
			.getSimpleName();
	private String mpersonalID;

	public AlarmClockDownloadTask(Context context, String persionID,
			CommCallback callback) {

		super(context, callback);
		mpersonalID = persionID;
	}

	@Override
	public void run() {
		try {

			Dao<AlarmClock, Integer> inputdao = getHelper(mcontext)
					.getAlarmClockDao();

			JSONObject serializedObj = new JSONObject();
			serializedObj.put("personID", mpersonalID);

			List<AlarmClock> list = inputdao
					.queryForEq("personID", mpersonalID);
			if (list.size() == 0) {
				serializedObj.put("maxSyncID1", "-1");
				serializedObj.put("maxSyncID2", "-1");
			} else if (list.size() == 1) {
				serializedObj.put("maxSyncID1", list.get(0).getSyncid()==null?"0":list.get(0).getSyncid());
				serializedObj.put("maxSyncID2", "-1");
			} else {
				serializedObj.put("maxSyncID1", list.get(0).getSyncid()==null?"0":list.get(0).getSyncid());
				serializedObj.put("maxSyncID2", list.get(1).getSyncid()==null?"0":list.get(1).getSyncid());
			}

			Map<String, String> parmas = new HashMap<String, String>();
			parmas.put("jsonstring", serializedObj.toString());

			String result = super.uploadByHTTP(parmas,
					ConstantData.AlarmClockDownloadURI);

			if (ServerResponseCode.parseOf(result) == ServerResponseCode.FAILED) {
				ccb.setCommResult(this, mpersonalID, ServerResponseCode.FAILED);
				return;
			}
			if (ServerResponseCode.parseOf(result) == ServerResponseCode.NOMORE) {
				ccb.setCommResult(this, mpersonalID, ServerResponseCode.NOMORE);
				return;
			}

			if (result.length() > 0) {
				AlarmClockListJsonWrapper<?> wapper = AlarmClockListJsonWrapper
						.getInstance(result, AlarmClockListJsonWrapper.class);
				// remove old
				inputdao.delete(list);
				//
				List<AlarmClock> inputlist = wapper.getMpps();
				for (AlarmClock input : inputlist) {
					inputdao.create(input);
					// reset the alarm clock.
					if (PersonProfileCache.getInstance(mcontext).getPersonID(mcontext)
							.equals(mpersonalID)) {

						if (input != null)
							setAlarm(input);
					}
				}
				ccb.setCommResult(this, mpersonalID, ServerResponseCode.SUCCESS);

			} else {
				ccb.setCommResult(this, mpersonalID, ServerResponseCode.FAILED);
			}

			return;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ccb.setCommResult(this, mpersonalID, ServerResponseCode.FAILED);
		}

	}

	@Override
	public DatabaseHelper getHelper(Context context) {

		return DatabaseAccessImplementation.getInstance().getHelper(mcontext);
	}

	private void setAlarm(AlarmClock ac) {

		Intent intent = new Intent(mcontext, AlarmReceiver.class);
		Bundle bundle = new Bundle();

		bundle.putString(ConstantData.HMBPERSONID, mpersonalID);
		bundle.putString("cycle", ac.getCycle());
		bundle.putString("startTime", ac.getStartTimeInMills());
		bundle.putString("alarmNum", ac.getClockid());
		bundle.putString("alarmDesc", ac.getDescription());
		intent.putExtras(bundle);

		PendingIntent pendingIntent = PendingIntent.getBroadcast(mcontext,
				Integer.valueOf(ac.getClockid()), intent, PendingIntent.FLAG_CANCEL_CURRENT);

		// 获取闹钟管理器
		AlarmManager alarmManager = (AlarmManager) mcontext
				.getSystemService(mcontext.ALARM_SERVICE);
		// 设置闹钟
		// setting time is in pass, so have to figure out new timer
		long repeat2 = AlarmRepeatCalculater.getNextAlarmTime(ac);

		if (repeat2 == 0)
			return;
		alarmManager.set(AlarmManager.RTC_WAKEUP, repeat2, pendingIntent);

		String timeStr = HealthDateUtil.formatDate(new Date(repeat2),
				"yyyy-MM-dd HH:mm:ss");
		Log.d(TAG, "set the time to " + timeStr);
	}
}
